package com.srit.core.ibatis.page;

import java.sql.Connection;
import java.sql.SQLException;

import com.ibatis.sqlmap.engine.execution.SqlExecutor;
import com.ibatis.sqlmap.engine.mapping.statement.RowHandlerCallback;
import com.ibatis.sqlmap.engine.scope.StatementScope;

public class XSqlExecutor extends SqlExecutor {
	private Dialect dialect;
	private boolean enableLimit = true;

	public Dialect getDialect() {
		return dialect;
	}

	public void setDialect(Dialect dialect) {
		this.dialect = dialect;
	}

	public boolean isEnableLimit() {
		return enableLimit;
	}

	public void setEnableLimit(boolean enableLimit) {
		this.enableLimit = enableLimit;
	}

	/**
	 * 重写SqlExecutor.executeQuery方法 实现ORACLE的SQL物理分页 see OracleDialect
	 */
	public void executeQuery(StatementScope statementScope, Connection conn,
			String sql, Object[] parameters, int skipResults, int maxResults,
			RowHandlerCallback callback) throws SQLException {
		if (isLimit(sql, skipResults, maxResults)) {
			// 有分页信息、可物理分页SQL
			sql = dialect.getOracleLimit(sql, skipResults, maxResults);// 获得物理分页SQL
			skipResults = NO_SKIPPED_RESULTS;// 设置skipResults为SqlExecutor不分页
			maxResults = NO_MAXIMUM_RESULTS;// 设置maxResults为SqlExecutor不分页
		}
		super.executeQuery(statementScope, conn, sql, parameters, skipResults,
				maxResults, callback);
	}

	/**
	 * 是否允许执行分页
	 * 
	 * @param sql
	 * @param skipResults
	 * @param maxResults
	 * @return
	 */
	private boolean isLimit(String sql, int skipResults, int maxResults) {
		return (skipResults != NO_SKIPPED_RESULTS || maxResults != NO_MAXIMUM_RESULTS)
				&& enableLimit && isSelect(sql);
	}

	/**
	 * 是否可物理分页SQL
	 * 
	 * @param sql
	 * @return
	 */
	private boolean isSelect(String sql) {
		if (sql.toLowerCase().indexOf("select") >= 0
				&& sql.toLowerCase().indexOf("rownum") == -1) {
			return true;
		}
		return false;
	}

}
